package platform

import (
	"fmt"
	"net/http"
	"strconv"

	"gitee.com/wangshh_123/cross-pay-go/src/middleware"
	"gitee.com/wangshh_123/cross-pay-go/src/models"
	platformCommon "gitee.com/wangshh_123/cross-pay-go/src/platform/common"
	"gitee.com/wangshh_123/cross-pay-go/src/utils/common"
	"gorm.io/gorm"

	"github.com/gin-gonic/gin"
	"github.com/shopspring/decimal"
)

// UpdateCard 更新卡片信息
func (c *UnifiedCardController) UpdateCard(ctx *gin.Context) {
	// 从中间件获取平台信息
	platformInfo, exists := middleware.GetPlatformInfoFromContext(ctx)
	if !exists {
		common.Error(ctx, http.StatusUnauthorized, "platform_info_not_found", nil)
		return
	}

	var req struct {
		CardID                     string   `json:"cardId" binding:"required"`
		RequestID                  string   `json:"requestId" binding:"required"`
		CardFormFactor             string   `json:"cardFormFactor" binding:"omitempty,oneof=virtual_card physical_card"`
		MaxOnDaily                 *int     `json:"maxOnDaily,omitempty"`
		MaxOnMonthly               *int     `json:"maxOnMonthly,omitempty"`
		MaxOnPercent               *int     `json:"maxOnPercent,omitempty"`
		Nickname                   string   `json:"nickname,omitempty"`
		TransactionLimit           *float64 `json:"transactionLimit,omitempty"`
		TransactionLimitType       string   `json:"transactionLimitType,omitempty" binding:"omitempty,oneof=limited unlimited"`
		TransactionLimitChangeType string   `json:"transactionLimitChangeType,omitempty" binding:"omitempty,oneof=increase decrease"`
	}

	if err := ctx.ShouldBindJSON(&req); err != nil {
		common.Error(ctx, http.StatusBadRequest, "invalid_params", err)
		return
	}

	// 构建统一的更新卡片请求
	updateCardRequest := &platformCommon.OpenCardRequest{
		RequestID:            req.RequestID,
		CardFormFactor:       req.CardFormFactor,
		TransactionLimit:     fmt.Sprintf("%v", req.TransactionLimit),
		TransactionLimitType: req.TransactionLimitType,
	}

	// 使用平台管理器处理更新卡片请求
	result, err := c.platformManager.HandleRequest(ctx.Request.Context(), platformInfo.PlatformType, "open_card", updateCardRequest)
	if err != nil {
		common.Error(ctx, http.StatusInternalServerError, "update_card_failed", err)
		return
	}

	common.Success(ctx, result)
}

// FreezeCard 冻结/解冻卡片
func (c *UnifiedCardController) FreezeCard(ctx *gin.Context) {
	// 从中间件获取平台信息
	platformInfo, exists := middleware.GetPlatformInfoFromContext(ctx)
	if !exists {
		common.Error(ctx, http.StatusUnauthorized, "platform_info_not_found", nil)
		return
	}

	var req struct {
		CardID    string `json:"cardId" binding:"required"`
		Status    string `json:"status" binding:"required,oneof=freeze unfreeze"`
		RequestId string `json:"requestId" binding:"required"`
	}

	if err := ctx.ShouldBindJSON(&req); err != nil {
		common.Error(ctx, http.StatusBadRequest, "invalid_params", err)
		return
	}

	// 构建统一的冻结卡片请求
	freezeCardRequest := &platformCommon.FreezeCardRequest{
		CardID: req.CardID,
	}

	// 使用平台管理器处理冻结卡片请求
	result, err := c.platformManager.HandleFreezeCard(ctx.Request.Context(), platformInfo.PlatformType, freezeCardRequest)
	if err != nil {
		common.Error(ctx, http.StatusInternalServerError, "freeze_card_failed", err)
		return
	}

	common.Success(ctx, result)
}

// CancelCard 注销卡片
func (c *UnifiedCardController) CancelCard(ctx *gin.Context) {
	// 从中间件获取平台信息
	platformInfo, exists := middleware.GetPlatformInfoFromContext(ctx)
	if !exists {
		common.Error(ctx, http.StatusUnauthorized, "platform_info_not_found", nil)
		return
	}

	var req struct {
		CardID          string  `json:"cardId" binding:"required"`
		RealTimeBalance float64 `json:"realTimeBalance" binding:"gte=0"`
	}

	if err := ctx.ShouldBindJSON(&req); err != nil {
		common.Error(ctx, http.StatusBadRequest, "invalid_params", err)
		return
	}

	// 构建统一的注销卡片请求
	cancelCardRequest := &platformCommon.CancelCardRequest{
		CardID: req.CardID,
	}

	// 使用平台管理器处理注销卡片请求
	result, err := c.platformManager.HandleCancelCard(ctx.Request.Context(), platformInfo.PlatformType, cancelCardRequest)
	if err != nil {
		common.Error(ctx, http.StatusInternalServerError, "cancel_card_failed", err)
		return
	}

	common.Success(ctx, result)
}

// RechargeCard 卡片充值
func (c *UnifiedCardController) RechargeCard(ctx *gin.Context) {
	// 从中间件获取平台信息
	platformInfo, exists := middleware.GetPlatformInfoFromContext(ctx)
	if !exists {
		common.Error(ctx, http.StatusUnauthorized, "platform_info_not_found", nil)
		return
	}

	var req struct {
		RequestId string      `json:"requestId" binding:"required"`
		CardId    string      `json:"cardId" binding:"required"`
		CardID    string      `json:"CardId"`                    // 支持大写CardId
		Amount    interface{} `json:"amount" binding:"required"` // 支持string和float64
	}

	if err := ctx.ShouldBindJSON(&req); err != nil {
		common.Error(ctx, http.StatusBadRequest, "invalid_params", err)
		return
	}

	// 处理CardId字段，支持两种大小写
	cardId := req.CardId
	if cardId == "" {
		cardId = req.CardID
	}

	// 处理Amount字段，支持字符串和数字
	var amount float64
	switch v := req.Amount.(type) {
	case string:
		var err error
		amount, err = strconv.ParseFloat(v, 64)
		if err != nil {
			common.Error(ctx, http.StatusBadRequest, "invalid_amount_format", err)
			return
		}
	case float64:
		amount = v
	case int:
		amount = float64(v)
	case int64:
		amount = float64(v)
	default:
		common.Error(ctx, http.StatusBadRequest, "invalid_amount_type", fmt.Errorf("amount must be string or number, got %T", req.Amount))
		return
	}

	// 构建统一的充值请求
	rechargeRequest := &platformCommon.RechargeCardRequest{
		RequestID: req.RequestId,
		CardID:    cardId,
		Amount:    amount,
	}

	// 使用平台管理器处理充值请求
	result, err := c.platformManager.HandleRechargeCard(ctx.Request.Context(), platformInfo.PlatformType, rechargeRequest)
	if err != nil {
		common.Error(ctx, http.StatusInternalServerError, "recharge_failed", err)
		return
	}

	common.Success(ctx, result)
}

// WithdrawCard 卡片提现
func (c *UnifiedCardController) WithdrawCard(ctx *gin.Context) {
	// 从中间件获取平台信息
	platformInfo, exists := middleware.GetPlatformInfoFromContext(ctx)
	if !exists {
		common.Error(ctx, http.StatusUnauthorized, "platform_info_not_found", nil)
		return
	}

	var req struct {
		CardId string      `json:"cardId" binding:"required"`
		Amount interface{} `json:"amount" binding:"required"`
		Remark string      `json:"remark,omitempty"`
	}

	if err := ctx.ShouldBindJSON(&req); err != nil {
		common.Error(ctx, http.StatusBadRequest, "invalid_params", err)
		return
	}

	// 处理Amount字段，支持字符串和数字
	var amount float64
	switch v := req.Amount.(type) {
	case string:
		var err error
		amount, err = strconv.ParseFloat(v, 64)
		if err != nil {
			common.Error(ctx, http.StatusBadRequest, "invalid_amount_format", err)
			return
		}
	case float64:
		amount = v
	case int:
		amount = float64(v)
	case int64:
		amount = float64(v)
	default:
		common.Error(ctx, http.StatusBadRequest, "invalid_amount_type", fmt.Errorf("amount must be string or number, got %T", req.Amount))
		return
	}

	// 构建统一的提现请求
	withdrawRequest := &platformCommon.WithdrawCardRequest{
		CardID: req.CardId,
		Amount: amount,
		Remark: req.Remark,
	}

	// 使用平台管理器处理提现请求
	result, err := c.platformManager.HandleWithdrawCard(ctx.Request.Context(), platformInfo.PlatformType, withdrawRequest)
	if err != nil {
		common.Error(ctx, http.StatusInternalServerError, "withdraw_failed", err)
		return
	}

	common.Success(ctx, result)
}

// RechargeReturn 卡金额退还
func (c *UnifiedCardController) RechargeReturn(ctx *gin.Context) {
	var req struct {
		CardId       string `json:"cardId" binding:"required"`
		ReturnAmount string `json:"returnAmount" binding:"required"`
		RequestId    string `json:"requestId" binding:"required"`
	}

	// 1. 参数验证
	if err := ctx.ShouldBindJSON(&req); err != nil {
		common.Error(ctx, http.StatusBadRequest, "invalid_request_body", err)
		return
	}

	// 2. 查询卡片信息
	var userCard models.UserCard
	if err := c.db.Where("card_id = ?", req.CardId).First(&userCard).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			common.Error(ctx, http.StatusNotFound, "card_not_found", fmt.Errorf("card %s not found", req.CardId))
		} else {
			common.Error(ctx, http.StatusInternalServerError, "query_card_failed", err)
		}
		return
	}

	// 3. 验证退还金额
	returnAmount, err := strconv.ParseFloat(req.ReturnAmount, 64)
	if err != nil {
		common.Error(ctx, http.StatusBadRequest, "invalid_amount_format", err)
		return
	}
	if userCard.TotalTransferAmount.LessThan(decimal.NewFromFloat(returnAmount)) {
		common.Error(ctx, http.StatusBadRequest, "refund_amount_exceeds_total",
			fmt.Errorf("refund amount %s exceeds total transfer amount %s",
				req.ReturnAmount, userCard.TotalTransferAmount.String()))
		return
	}

	// 4. 这里应调用具体平台的退还逻辑或本地处理逻辑
	common.Success(ctx, gin.H{"message": "RechargeReturn - 功能待实现"})
}
